package com.klasster.recruitmentPlatform.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.klasster.recruitmentPlatform.domain.po.User;
import com.klasster.recruitmentPlatform.service.impl.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class TokenUtil {

    /**
     * 密钥
     */
    private static final String SECRET_KEY = "klasster-recruitment-platform";

    /**
     * token有效时长
     */
    private static final long EXPIRATION_TIME = 1000L * 60 * 60 * 24 * 30;


    private final UserServiceImpl userService;


    /**
     * 生成token
     * @param user_id 用户id
     * @return token
     */
    public String generateToken(Long user_id, String password) {
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        return JWT.create().withHeader(map)
                .withClaim("user_id",user_id)
                .withClaim("password",password)
                .withSubject("klasster")
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * 解析token
     * @param token token
     * @return token内容
     */
    private Map<String, Claim> verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
        DecodedJWT jwt;
        try {
            jwt = verifier.verify(token);
        } catch (JWTVerificationException e) {
            return null;
        }
        return jwt.getClaims();
    }

    /**
     * 根据token获取用户id
     * @param token token
     * @return 用户id
     */
    public Long getUserID(String token) {
        Map<String, Claim> claims = verifyToken(token);
        if(claims==null)
            return null;
        return claims.get("user_id").asLong();
    }

    /**
     * 验证token是否有效
     * @param token token
     * @return 有效性
     */
    public boolean checkToken(String token) {
        Map<String, Claim> claims = verifyToken(token);
        // token无效
        if(claims==null) {
            return false;
        }
        Long user_id = claims.get("user_id").asLong();
        String password = claims.get("password").asString();
        //检查用户名和密码是否正确
        User user = userService.getById(user_id);
        if(user==null) {
            return false;
        }
        return user.getPassword().equals(password);
    }


}
